package com.admin.action;

import com.alibaba.fastjson.JSON;
import com.uni.entity.Commodity;
import com.uni.entity.CommodityRecord;
import com.uni.entity.User;
import com.uni.service.Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * --------------project-------------
 *
 * @Author Unirithe  - Mr.Chao
 * - CSDN:
 * https://blog.csdn.net/Unirithe
 * - GitHub:
 * https://github.com/unirithe
 * @create 2021/12/29 12:38
 * ------------------------------------------
 */
@WebServlet(name = "etReadUserAction", urlPatterns = "/etReadUserAction")
public class etReadUserAction extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        req.setCharacterEncoding("UTF-8");
        resp.setHeader("content-type", "text/json;charset=utf-8");
        Map<String , Integer> map_user_action = new HashMap<>();
        Map<String, Integer> map_commodity_scan = new HashMap<>();
        for (User user : Service.user.queryAllUser()) {
            // 当前用户user的所有浏览记录
            map_user_action.put(user.getName(), 0);
            for (CommodityRecord commodityRecord : Service.user.queryHistory(user)) {
                Commodity commodity = commodityRecord.getCommodity();
                map_user_action.put(user.getName(), map_user_action.get(user.getName()) + 1);
                map_commodity_scan.put(commodity.getTypeName(),
                        map_commodity_scan.getOrDefault(commodity.getTypeName(), 0) + 1);
            }
        }
        Map<String, Map> map = new HashMap<>();
        map.put("user", map_user_action);
        map.put("commodity", map_commodity_scan);
        resp.getWriter().write(JSON.toJSONString(map));

    }
}
